package com.lawyer.uitls;

import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Base64;
import java.util.Map;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

public class CertificatesUitl {

	public static Map<String, String> getToken(Map<String, String> map) throws UnsupportedEncodingException {
		String message = buildMessage(map.get("appId"), map.get("timeStamp"), map.get("nonceStr"), map.get("package"));
		String signature = sign(message.getBytes("utf-8"));
		map.put("paySign", signature);
		return map ;
	}

	public static String sign(byte[] message) {
		try {
			Signature sign = Signature.getInstance("SHA256withRSA");
			Resource privateKey = new DefaultResourceLoader().getResource("classpath:template/apiclient_key.pem");
			PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(privateKey.getInputStream());
			sign.initSign(merchantPrivateKey);
			sign.update(message);
			return Base64.getEncoder().encodeToString(sign.sign());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	public static String buildMessage(String appId, String timeStamp, String nonceStr, String packageStr) {
		return appId + "\n" + timeStamp + "\n" + nonceStr + "\n" + packageStr+ "\n";
	}

}
